<template>
    <el-dialog
        v-model="centerDialogVisible"
        title="添加商品信息"
        width="50%"
        center
        @close="closeDialog(false)"
    >
        <el-form ref="validateForm" :model="goodsForm" :rules="rules" label-width="120px">
            <el-form-item label="商品名称" prop="name">
                <el-input v-model="goodsForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
                <el-input v-model="goodsForm.price"></el-input>
            </el-form-item>

            <el-form-item label="商品图片" prop="picture">
                <el-upload
                    class="avatar-uploader"
                    :action="uploadURL"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="handleBeforeUpload"
                >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="商品评价" prop="star">
                <el-input v-model="goodsForm.star"></el-input>
            </el-form-item>
            <el-form-item label="商品类型" prop="typeName">
                <el-select v-model="goodsForm.typeName" placeholder="请选择商品类型">
                    <el-option
                        v-for="item in typeList"
                        :label="item"
                        :key="item.length"
                        :value="item"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品详情" prop="intro">
                <!-- <QuillEditor theme="snow" ref="editor" /> -->
                <el-input type="textarea" rows="5" v-model="goodsForm.intro"></el-input>
            </el-form-item>
            <el-form-item style="margin-top:80px; ">
                <el-button type="primary" @click="submitAdd">添加商品</el-button>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button
                    @click="() => {
                        closeDialog(false);
                    }"
                >取消</el-button>
                <el-button type="primary" @click="submitAdd">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { reactive, toRefs, ref, onMounted } from 'vue';
// npm install @vueup/vue-quill@beta --save
// import { QuillEditor } from '@vueup/vue-quill';
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { Plus } from '@element-plus/icons';
import axios from 'axios';
import { ElMessage } from "element-plus";

// 添加商品的方法
function useSubmitAdd(state, validateForm, emit) {
    const submitAdd = () => {
        validateForm.value.validate((valid) => {
            if (valid) {

                let yy = new Date().getFullYear();
                let mm = new Date().getMonth() + 1;
                let dd = new Date().getDate();
                let ddate = yy + "-" + mm + "-" + dd;

                const params = {
                    name: state.goodsForm.name,
                    price: state.goodsForm.price,
                    thumbnail: state.goodsForm.picture,
                    star: state.goodsForm.star,
                    intro: state.goodsForm.intro,
                    typeName: state.goodsForm.typeName,
                    pubdate: ddate,
                };
                // 执行商品提交操作
                axios({
                    url: '/addGoods',
                    method: 'get',
                    params: params,
                }).then(res => {
                    validateForm.value.resetFields(); //重置表单
                    emit('onCloseDialog', false, res.data.data);
                });
            }
        })
    }
    return {
        submitAdd,
    }
}

// 完成文件上传类型校验
const handleBeforeUpload = (file) =>{
    const arr = file.name.split('.')[1]
    console.log(arr);
    if(!["jpg","jpeg","png"].includes(arr)){
        ElMessage.error('请上传jpg,jpeg,png类型的图片文件');
        return false;
    }
}

export default {
    components: {
        Plus,
    },
    props: {
        centerDialogVisible: Boolean,
    },
    emits: ["onCloseDialog"],    // 声明，保存传递过来的事件
    setup(props, { emit }) {
        const validateForm = ref();
        const state = reactive({
            centerDialogVisible: props.centerDialogVisible,
            uploadURL: import.meta.env.VITE_APP_URL + "/goodsFileUpload",
            imageUrl: "",
            goodsForm: {
                name: "",
                price: 0,
                picture: "",
                intro: "",
                typeName: [],
                pubdate: "",
            },

        });

        const closeDialog = (visible) => {
            state.imageUrl = "";
            emit('onCloseDialog', visible);
        };
        // 上传成功后，执行的处理函数
        const handleAvatarSuccess = (response) => {
            // 预览显示上传成功的图片
            state.imageUrl = import.meta.env.VITE_APP_URL + response.data;
            state.goodsForm.picture = response.data;
        };
        const rules = {
            name: [{
                required: true,
                message: '请输入商品名称',
                trigger: 'blur',
            }],
            price: [{
                required: true,
                message: '请输入商品价格',
                trigger: 'blur',
            }],
            picture: [{
                required: true,
                message: '请选择商品图片',
                trigger: 'blur',
            }],
            star: [{
                required: true,
                message: '请输入商品评价1-5',
                trigger: 'blur',
            }],
            intro: [{
                required: true,
                message: '请输入商品介绍',
                trigger: 'blur',
            }],

        }
        return {
            ...toRefs(state),
            closeDialog,
            rules,
            handleAvatarSuccess,
            ...useSubmitAdd(state, validateForm, emit),
            validateForm,
            handleBeforeUpload
        }
    },
    data() {
        let typeList = [];
        axios({
            url: '/getGoodsType',
            method: 'get',
        }).then(res => {
            // console.log(res.data.data)
            // res.data.data.forEach(element => {
            // state.goodsForm.typeName.push(element.name)
            var u = res.data.data;
            var i = 0;
            for (i; i < u.length; i++) {
                // state.goodsForm.typeName.push(u[i].name)
                typeList.push(u[i].name)
            }
            // });
        });
        return {
            typeList: typeList,
        }
    },
}
</script>

<style>
/* 上传组件 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
/* .avatar-uploader-icon svg {
    margin-top: 74px; 
} */
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>